import { Injectable } from '@nestjs/common';
import {
  createWriteStream,
  existsSync,
  mkdirSync,
  readdirSync,
  readFileSync,
  unlinkSync,
  writeFileSync,
} from 'fs';
import { join } from 'path';

@Injectable()
export class UploadService {
  private readonly CHUNKS_DIR = join(
    __dirname,
    '..',
    '..',
    'uploads',
    'chunks'
  );

  constructor() {
    if (!existsSync(this.CHUNKS_DIR)) {
      mkdirSync(this.CHUNKS_DIR, { recursive: true });
    }
  }

  // 保存单个切片
  saveChunk(uploadId: string, chunkIndex: number, buffer: Buffer) {
    const uploadDir = join(this.CHUNKS_DIR, uploadId);
    if (!existsSync(uploadDir)) {
      mkdirSync(uploadDir, { recursive: true });
    }
    const chunkPath = join(uploadDir, chunkIndex.toString());
    writeFileSync(chunkPath, buffer);
  }

  mergeChunks(uploadId: string, filename: string): string {
    const uploadDir = join(this.CHUNKS_DIR, uploadId);
    if (!existsSync(uploadDir)) {
      throw new Error('Upload not found');
    }
    const chunkFiles = readdirSync(uploadDir)
      .map(name => parseInt(name, 10))
      .sort((a, b) => a - b);

    const finalPath = join(__dirname, '..', '..', 'uploads', filename);
    const writeStream = createWriteStream(finalPath);

    for (const index of chunkFiles) {
      const chunkPath = join(uploadDir, index.toString());
      const chunkData = readFileSync(chunkPath);
      writeStream.write(chunkData);
      unlinkSync(chunkPath); // 可选：合并后删除分片
    }

    writeStream.end();
    return finalPath;
  }
}
